//
//  HLStatuses.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/3/2.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit

class HLStatuses: NSObject {

    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    
    /// 字符串型的微博ID
    var idstr: String?
    
    //微博信息内容
     var text: String?
    
    //微博来源 <a href="http://app.weibo.com/t/feed/5hCtyG" rel="nofollow">红米2</a>
    var source: String? {
        didSet {
            // 在didSet方法中给自己赋值不会再调用didSet方法
            source = source?.regularType()
        }
    }
    
    //微博作者的用户信息字段 详细
    var user: HLStatusesUser?
    
    //转发数
    var reposts_count: Int = 0
    
    //评论数
    var comments_count: Int = 0
    
    //表态数
    var attitudes_count: Int = 0
    
    //表态数 微博配图ID。多图时返回多图ID [[AnyObject]]数组里面存放的是字典
    var pic_urls: [[String:AnyObject]]? {
        didSet {
            if pic_urls != nil && pic_urls?.count != 0 {
                
                storePictureUrl = [NSURL]()
                for dict in pic_urls! {
                    let urlStr = dict["thumbnail_pic"] as! String
                    let url = NSURL(string: urlStr)!
                    storePictureUrl?.append(url)
                }
            }

        }
    }
    
    /// 自定义属性 返回保存图片url字典数组转为模型数组
    var storePictureUrl:[NSURL]?
    
    /// 被转发的微博
    var retweeted_status :HLStatuses?
    
    
    // 重写初始化方法
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // 使用kvc赋值  实际上就是在以这个方法在赋值
    override func setValue(value: AnyObject?, forKey key: String) {
        //模型中的属性还有是字典的就在这里找到模型中字典的key然后转换为模型
        if key == "user" {
            if let dict = value as? [String:AnyObject] {
                user = HLStatusesUser(dict: dict)
            }
            return // 使用return禁止调用父类的默认方法
        }
        
        // 拦截retweeted_status 这个key把字典转为模型
        if key == "retweeted_status" {
            /// 先判断能否转成是字典
            if let dict = value as? [String :AnyObject] {
                retweeted_status = HLStatuses(dict: dict)
            }
            return // 一定得终止 不然我们前面做的事情会被覆盖
        }
        
        super.setValue(value, forKey: key)
    }
    
    // 重写forUndefinedKey方法 防止key多 报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    //重写输出方法
    override var description: String {
        let keys = ["created_at","id","idstr","text","source","user","reposts_count","comments_count","attitudes_count","attitudes_count","idstr","pic_urls"];
        
        return "\n\tstatuses模型:\(dictionaryWithValuesForKeys(keys).description)"
    }
    
}
